#pragma once

#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <cerrno>
#include <cstring>
#include <string>
#include <functional>
#include "Log.hpp"
#include "InetAddr.hpp"

enum
{
    SOCKET_ERROR = 1,
    BIND_ERROR,
    USAGE_ERROR
};

const static int defaultfd = -1;

using func_t = std::function<std::string(const std::string &, bool &ok)>;

class UdpServer
{
public:
    UdpServer(uint16_t port, func_t func) : _sockfd(defaultfd), _port(port), _isrunning(false), _func(func)
    {
    }

    void InitServer()
    {
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
        if (_sockfd < 0)
        {
            LOG(FATAL, "socket error, %s, %d\n", strerror(errno), errno);
            exit(SOCKET_ERROR);
        }

        struct sockaddr_in local;
        bzero(&local, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);
        // local.sin_addr.s_addr = inet_addr(_ip.c_str());
        local.sin_addr.s_addr = INADDR_ANY;

        int n = bind(_sockfd, (struct sockaddr *)&local, sizeof(local));
        if (n < 0)
        {
            LOG(FATAL, "bind error, %s, %d\n", strerror(errno), errno);
        }
        LOG(INFO, "sock bind success\n");
    }

    void Start()
    {
        _isrunning = true;
        while (true)
        {
            char request[1024];
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer); // 必须初始化成为sizeof(peer)
            ssize_t n = recvfrom(_sockfd, request, sizeof(request) - 1, 80, (struct sockaddr *)&peer, &len);
            if (n > 0)
            {
                request[n] = 0;
                InetAddr addr(peer);
                LOG(DEBUG, "get message from [%s:%d]: %s\n", addr.Ip().c_str(), addr.Port(), request);

                bool ok;
                std::string response = _func(request, ok); // 将请求回调出去，在外部进行数据处理

                sendto(_sockfd, response.c_str(), response.size(), 0, (struct sockaddr *)&peer, len);
            }
        }
        _isrunning = false;
    }

private:
    int _sockfd;
    uint16_t _port;
    // std::string _ip; //不需要
    bool _isrunning;

    // 给服务器设定回调，用来让上层进行注册业务的处理方法
    func_t _func;
};
